#-*- coding:utf-8 -*-
from __future__ import unicode_literals

import cookielib
import datetime
import json
import re
import ssl
import time
import urllib
import urllib2

import damatuWeb

from sendmail import sendmail
from station_names import station_names
tmp_list=[]
c=cookielib.LWPCookieJar()
cookie=urllib2.HTTPCookieProcessor(c)
opener=urllib2.build_opener(cookie)
urllib2.install_opener(opener)
ssl._create_default_https_context=ssl._create_unverified_context
seat={'二等座':'O','一等座':'M','硬卧':'3','软卧':'4','硬座':'1','无座':'1'}
city={}
city2={}
seatType=''
s1=''
s2=''
username=''#15764230482
password=''#yf296349469
station_names=station_names.decode('utf-8')
for i in station_names.split('@'):
    if not i:
        continue
    tmp_list=i.split('|')
    city[tmp_list[1]]=tmp_list[2]
    city2[tmp_list[2]]=tmp_list[1]



orderlist={
    "train_date":"2017-10-24",  #日期
    "tk":"杭州",                #出发地
    "ar":"上海",                #到达地
    'choose_seats':"二等座",          #座位
    "train_no":[],#["K1558"],   #车次
    "passenger_name":"杨帆,刘洋",#乘坐人
    's1':'',
    's2':'',
}


#searchTrain()
if orderlist.get('choose_seats'):seatType=seat[orderlist.get('choose_seats')]
train_date=orderlist.get('train_date')
tk=orderlist.get('tk')#'南宁东'
ar=orderlist.get('ar')#'三水'
from_station=city[tk]
to_station=city[ar]
n=0

def getPage(url,data=None,timeout=15):
    try:
        headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
        'Referer':'https://kyfw.12306.cn/otn/leftTicket/init',
        }
        req=urllib2.Request(url,data=data,headers=headers)
        h=opener.open(req,timeout=timeout)
        if h.getcode()==200:
            return h.read()
        elif h.getcode()==302:
            getPage(h.geturl())
        else:
            print (h.getcode())
    except Exception as e:
        print(url,e)

def getQurl():
    h=getPage('https://kyfw.12306.cn/otn/leftTicket/init')
    if h:#获取主页
        CLeftTicketUrl=re.findall("var CLeftTicketUrl = '(.*?)';",h)[0] #获取抢票地址
        if CLeftTicketUrl:
            return CLeftTicketUrl
        else:
            print ('查票地址获取失败!')
            return None
CLeftTicketUrl=getQurl()
def getCode():
    codeimg=getPage('https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand')
    with open('code.png','wb') as f:
        f.write(codeimg) 
def code():
    getCode()
    cod= damatuWeb.codeCal()
    print(cod)
    data={
        'answer':cod,
        'login_site':'E',
        'rand':'sjrand',
        }
    data=urllib.urlencode(data)
    h=getPage('https://kyfw.12306.cn/passport/captcha/captcha-check',data=data)
    h=json.loads(h)
    if h and h['result_code']=='4':
        print(h['result_message'])
        login()
        return True
    else:
        print(h['result_message'])
        code()
def code2(username,password):
    getCode()
    cod= damatuWeb.codeCal()
    print(cod)
    data={
        'answer':cod,
        'login_site':'E',
        'rand':'sjrand',
        }
    data=urllib.urlencode(data)
    h=getPage('https://kyfw.12306.cn/passport/captcha/captcha-check',data=data)
    h=json.loads(h)
    if h and h['result_code']=='4':
        print(h['result_message'])
        login_user=login(username,password)
        return login_user
    else:
        print(h['result_message'])
        code2(username,password)

def login(username,password):
    data={
        'username':username,
        'password':password,
        'appid':'otn',
        }
    data=urllib.urlencode(data)
    req=urllib2.Request('https://kyfw.12306.cn/passport/web/login',data=data)
    h=opener.open(req).read()
    h=json.loads(h)
    if h['result_code']==0:
        print(h["result_message"])
        req=urllib2.Request('https://kyfw.12306.cn/passport/web/auth/uamtk',data='appid=otn')
        print('登陆成功后获取newapptk:')
        h=opener.open(req).read()
        print (h)
        if h:
            newapptk=json.loads(h).get('newapptk')
            print ('发送请求newapptk')
            req=urllib2.Request('https://kyfw.12306.cn/otn/uamauthclient',data='tk=%s'%newapptk)
            h=opener.open(req).read()
            if h:
                apptk=json.loads(h).get('apptk')
                print (h)
                #c.save(ignore_expires=True,ignore_discard=True)
                return json.loads(h).get('username')
    else:
        print(h["result_message"])
        return False

def getTrain(CLeftTicketUrl,train_date,from_station,to_station):
    url='https://kyfw.12306.cn/otn/%s?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(CLeftTicketUrl,train_date,from_station,to_station)
    #print url
    h=getPage(url).decode('utf-8')
    #print h
    #if h:
        #print h
    #else:
        #print 'h没有值'
    if '网络可能存在问题' not in h:
        h=json.loads(h)
        if h['httpstatus']==200:
            return h['data']['result']
    else:
        print('网络可能存在问题,3秒后重试!')
        return False
def getTrain2(CLeftTicketUrl,train_date,from_station,to_station):
    url='https://kyfw.12306.cn/otn/%s?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT'%(CLeftTicketUrl,train_date,from_station,to_station)
    h=getPage(url).decode('utf-8')
    #print h
    #if h:
        #print h
    #else:
        #print 'h没有值'
    if '网络可能存在问题' not in h:
        h=json.loads(h)
        if h['httpstatus']==200:
            data=[]
            for i in h['data']['result']:
                t=i.split("|")
                t[6]=city2.get(i.split("|")[6])
                t[7]=city2.get(i.split("|")[7])
                data.append(t)
            return data
    else:
        print('网络可能存在问题,3秒后重试!')
        return False

def initDc():
    print ('>>>初始化2个参数')
    h=getPage('https://kyfw.12306.cn/otn/confirmPassenger/initDc',data='_json_att=')
    rp=re.findall("var globalRepeatSubmitToken = '(.*?)'",h)[0]
    key_check_isChange = re.findall(r"key_check_isChange':'(.*?)'",h)[0]
    return rp,key_check_isChange


def getPassenger(rp,key_check_isChange):
    data = {
            '_json_att':'',
            'REPEAT_SUBMIT_TOKEN':rp
        }
    data = urllib.urlencode(data)
    h=getPage('https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs',data=data)
    h=json.loads(h)
    print ('>>>获取乘客信息以供选择:')
    n=0
    for k in h["data"]["normal_passengers"]:
        print (n,k['passenger_name'],k['passenger_id_no'],k['mobile_no'])
        n+=1
    print ('>>>获取乘客信息')#下单环节3
    num=raw_input('请选择乘客(0~8),多个乘客请输入(0,1):')
    num=num.split(',')
    s1=''
    s2=''
    for i in num:
        s1+='%s,0,1,%s,1,%s,%s,N_'%(seatType,h["data"]["normal_passengers"][int(i)]["passenger_name"],h["data"]["normal_passengers"][int(i)]["passenger_id_no"],h["data"]["normal_passengers"][int(i)]["mobile_no"])
        s2+='%s,1,%s,1_'%(h["data"]["normal_passengers"][int(i)]["passenger_name"],h["data"]["normal_passengers"][int(i)]["passenger_id_no"])
    return s1,s2

def dealInfo(a):
    a=a.replace("'",'"')
    b=a.split(',{')
    n=0
    list1=[]
    list2=[]
    s=''
    s1=''
    s2=''
    for i in a:
        if i!='}':
            s+=i
        else:
            s+=i
            list1.append(s)
            s=''
    for i in list1:
        i=i.replace(',{','{')
        i=i.replace("'",'"')
        k=json.loads(i)
        list2.append((n,k['passenger_name'],k['passenger_id_no'],k['mobile_no']))
        print (n,k['passenger_name'],k['passenger_id_no'],k['mobile_no'])
        if orderlist.get("passenger_name"):
            if ',' in orderlist.get("passenger_name"):
                for j in orderlist.get("passenger_name").split(','):
                    if j==k['passenger_name']:
                        s1+='%s,0,1,%s,1,%s,%s,N_'%(seatType,k['passenger_name'],k['passenger_id_no'],k['mobile_no'])
                        s2+='%s,1,%s,1_'%(k['passenger_name'],k['passenger_id_no'])
            else:
                if orderlist.get("passenger_name")==k['passenger_name']:
                        s1+='%s,0,1,%s,1,%s,%s,N_'%(seatType,k['passenger_name'],k['passenger_id_no'],k['mobile_no'])
                        s2+='%s,1,%s,1_'%(k['passenger_name'],k['passenger_id_no'])
        n+=1
    print (s1,s2,list2)
    return s1,s2,list2

def getPassInfo():
    h=getPage('https://kyfw.12306.cn/otn/passengers/init').decode('utf-8')
    #if 'globalRepeatSubmitToken = null'not in h:c.save(ignore_expires=True,ignore_discard=True)
    if 'var passengers=[' in h:
        print ('>>>从我的乘车人获取乘客信息!')
        p=h.split('var passengers=[')[1].split('];')[0]
        s1,s2,list2=dealInfo(p)
        #c.save(ignore_expires=True,ignore_discard=True)
        return s1,s2,list2
    elif 'globalRepeatSubmitToken = null' in h:
        print ('>>>重新登陆中!!!')
        code()
        s1,s2,list2=getPassInfo()
        return s1,s2,list2


def checkOrderInfo(s1,s2,rp):
    print ('>>>检查订单信息')
    data = {
        'cancel_flag':'2',
        'bed_level_order_num':'000000000000000000000000000000',
        'passengerTicketStr':s1.encode('utf-8'),
        'oldPassengerStr':s2.encode('utf-8'),
        'tour_flag':'dc',
        'randCode':'',
        '_json_att':'',
        'REPEAT_SUBMIT_TOKEN':rp
    }
    data=urllib.urlencode(data)
    h=getPage('https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo',data=data)
    print ('确认订单信息:',h)

def getQueueCount(seatType,from_station,to_station,rp):
    print ('>>>查询当前剩余的票数:')
    global tmp_list
    data={
        'train_date':'Thu Oct 14 2017 00:00:00 GMT+0800 (中国标准时间)'.encode('utf-8'),
        'train_no':tmp_list[2],
        'stationTrainCode':tmp_list[3],
        'seatType':seatType,
        'fromStationTelecode':from_station,
        'toStationTelecode':to_station,
        'leftTicket':tmp_list[12],
        'purpose_codes':'00',
        'train_location':tmp_list[15],
        '_json_att':'',
        'REPEAT_SUBMIT_TOKEN':rp,
    }
    data=urllib.urlencode(data)
    h=getPage('https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount',data=data)
    print (h)
def confirmOrder(s1,s2,rp,key_check_isChange):
        print ('>>>准备提交订单!')
        global tmp_list
        data = {
            'passengerTicketStr':s1.encode('utf-8'),
            'oldPassengerStr':s2.encode('utf-8'),
            'randCode':'',
            'purpose_codes':'00',
            'key_check_isChange':key_check_isChange,
            'leftTicketStr':tmp_list[12],
            'train_location':tmp_list[15],
            'choose_seats':'',#1F
            'seatDetailType':'000',
            'roomType':'00',
            'dwAll':'N',
            '_json_att':'',
            'REPEAT_SUBMIT_TOKEN':rp
        }
        data=urllib.urlencode(data)
        h=getPage('https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue',data=data)
        if h:
            #c.save(ignore_expires=True,ignore_discard=True)
            if json.loads(h)["data"]["submitStatus"]:
                print ('>>>车票自动提交成功\n',h)
                print ('>>>正在获取订单结果!')
                if getResult(rp)==1:
                    print ('>>>发送通知邮件!')
                    sendmail('296349469@qq.com','%s-%s抢票结果%s过期'%(tk,ar,(datetime.datetime.now()+datetime.timedelta(minutes=29)).strftime('%Y-%m-%d %H:%M:%S')),'您订购的%s-%s,时间%s-%s,历时%s车次为%s的车票已经于%s抢票成功,请在%s前登陆12306完成支付!'%(tk,ar,tmp_list[8],tmp_list[9],tmp_list[10],tmp_list[3],time.strftime('%Y-%m-%d %H:%M:%S'),(datetime.datetime.now()+datetime.timedelta(minutes=29)).strftime('%Y-%m-%d %H:%M:%S')))
                    return True
                else:
                    return True
            else:
                print ('>>>下单不成功,错误提示是:\n',h)
                if json.loads(h)["data"]["errMsg"]=="验证码输入错误！":
                    code()
                return False
        else:
            print ('>>>自动提交请求返回的响应为空!')
def checkUser():
    print ('>>>执行checkUser检查用户状态是否有效!')
    h=getPage('https://kyfw.12306.cn/otn/login/checkUser',data='_json_att=')
    print (h)
    return h

def submitOrderRequest(secretStr,train_date,tk,ar):
    print ('>>>有票进入预定界面')
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    data='secretStr=%s&train_date=%s&back_train_date=%s&tour_flag=dc&purpose_codes=ADULT&query_from_station_name=%s&query_to_station_name=%s&undefined'%(secretStr,train_date,time.strftime('%Y-%m-%d'),tk,ar)
    h=getPage('https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest',data=data)
    if 'globalRepeatSubmitToken = null' in h:
        print ('>>>登陆已失效,重新登陆中')
        code()
        submitOrderRequest(secretStr,train_date,tk,ar)
        return h
    else:
        return h

def getResult(rp):
    h=getPage('https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?random=%s&tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN=%s'%(int(time.time()),rp))
    #print h
    h=json.loads(h)
    if h['data'].get('msg'):
        print (h['data']['msg'])
        if '对不起' in h['data']['msg']:
            return False
        else:
            return True
    else:
        print ('>>>未获取到结果,3秒后再试!')
        time.sleep(2)
        getResult(rp)



def order(secretStr):
    try:
        s1=orderlist.get('s1')
        s2=orderlist.get('s2')
        try:
            print ('>>>正在尝试从cookie中获取登陆信息!')
            #c.load(ignore_expires=True,ignore_discard=True)
        except:
            pass
        if orderlist.get("passenger_name") and (not s1 or not s2):
            s1,s2=getPassInfo() #获取乘客信息
        h=checkUser()
        if h and json.loads(h)['data']['flag']:
            h=submitOrderRequest(secretStr,train_date,tk,ar)
            if "您还有未处理的订单" in h:
                print ("有未完成订单!请先处理!")
                return True
            else:
                print( h)
            rp,key_check_isChange=initDc()
            if not s1 or not s2:s1,s2=getPassenger(rp,key_check_isChange)
            checkOrderInfo(s1,s2,rp)
            getQueueCount(seatType,from_station,to_station,rp)
            if confirmOrder(s1,s2,rp,key_check_isChange):
                return True

        else:
            print ('>>>没有登陆,正在重新登陆!')
            if code():
                if order(secretStr):
                    return True
                else:
                    return False
            else:
                code()
    except:
        raise
def printTrain():
    global tmp_list,n
    print ('[%s]%s %s [%s-%s] 历时:%s 二等:%s 一等:%s 硬座:%s 硬卧:%s 软卧:%s 无座:%s '%(n,tmp_list[13],tmp_list[3],tmp_list[8],tmp_list[9],tmp_list[10],tmp_list[30],tmp_list[31],tmp_list[29],tmp_list[28],tmp_list[23],tmp_list[26]))
    secretStr=tmp_list[0]
    if secretStr:
        print ('>>>查找到有票的车次,正在进入自动下单环节!')
        if order(secretStr):
            return True
def findtrain(train_no,train_date,from_station,to_station):
    try:
        html=getTrain(CLeftTicketUrl,train_date,from_station,to_station)
        #print html
        while not html:
            time.sleep(3)
            html=getTrain(CLeftTicketUrl,train_date,from_station,to_station)
        global n
        global seatType
        global tmp_list
        n+=1
        print ('>>>第%s次'%n,time.strftime('%H:%M:%S'),'查找车票中...')
        #print '>>>查找到以下车次信息:'
        for i in html:
            tmp_list=i.split('|')
            if train_no:#指定车次
                if orderlist['choose_seats']=='二等座':
                    if tmp_list[3] in train_no:print ('[%s]%s 二等座:%s'%(n,tmp_list[3],tmp_list[30]))
                    if tmp_list[3] in train_no and tmp_list[30] !='无' and tmp_list[30] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='一等座':
                    if tmp_list[3] in train_no:print ('[%s]%s 一等座:%s'%(n,tmp_list[3],tmp_list[31]))
                    if tmp_list[3] in train_no and tmp_list[31] !='无' and tmp_list[31] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='硬卧':
                    if tmp_list[3] in train_no:print ('[%s]%s 硬卧:%s'%(n,tmp_list[3],tmp_list[28]))
                    if tmp_list[3] in train_no and tmp_list[28] !='无' and tmp_list[28] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='软卧':
                    if tmp_list[3] in train_no:print( '[%s]%s 软卧:%s'%(n,tmp_list[3],tmp_list[23]))
                    if tmp_list[3] in train_no and tmp_list[23] !='无' and tmp_list[23] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='硬座':
                    if tmp_list[3] in train_no:print ('[%s]%s 硬座:%s'%(n,tmp_list[3],tmp_list[29]))
                    if tmp_list[3] in train_no and tmp_list[29] !='无' and tmp_list[29] !='':
                        return printTrain()
                else:
                    print ('>>>选座条件:指定车次,座位不限!')
                    #if tmp_list[3] in train_no:print '[%s]%s 二等:%s'%(n,tmp_list[3],tmp_list[30])
                    if tmp_list[3] in train_no:
                        if tmp_list[30] !='无' and tmp_list[30] !='':
                            print ('选了二等座')
                            seatType='O'
                            return printTrain()
                        elif tmp_list[31] !='无' and tmp_list[31] !='':
                            print ('选了一等座')
                            seatType='M'
                            return printTrain()
                        elif tmp_list[28] !='无' and tmp_list[28] !='':
                            print ('选了硬卧')
                            seatType='3'
                            return printTrain()
                        elif tmp_list[29] !='无' and tmp_list[29] !='':
                            print ('选了硬座')
                            seatType='1'
                            return printTrain()
                        elif tmp_list[23] !='无' and tmp_list[23] !='':
                            seatType='4'
                            return printTrain()

            else:#不指定车次
                if orderlist['choose_seats']=='二等座':
                    if tmp_list[30] !='无' and tmp_list[30] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='一等座':
                    if tmp_list[31] !='无' and tmp_list[31] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='硬卧':
                    if tmp_list[28] !='无' and tmp_list[28] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='软卧':
                    if tmp_list[23] !='无' and tmp_list[23] !='':
                        return printTrain()
                elif orderlist['choose_seats']=='硬座':
                    if tmp_list[29] !='无' and tmp_list[29] !='':
                        return printTrain()
                else:
                    print ('>>>选座条件:有座位就行,座位不限')
                    if tmp_list[30] !='无' and tmp_list[30] !='':
                        print ('选了二等座')
                        seatType='O'
                        return printTrain()
                    elif tmp_list[31] !='无' and tmp_list[31] !='':
                        print ('选了一等座')
                        seatType='M'
                        return printTrain()
                    elif tmp_list[28] !='无' and tmp_list[28] !='':
                        print ('选了硬卧')
                        seatType='3'
                        return printTrain()
                    elif tmp_list[29] !='无' and tmp_list[29] !='':
                        print ('选了硬座')
                        seatType='1'
                        return printTrain()
                    elif tmp_list[23] !='无' and tmp_list[23] !='':
                        seatType='4'
                        return printTrain()
    except Exception as e:
        print( e)
        time.sleep(3)

def searchTrain():
    print( '>>>欢迎进入自动购票系统! [By侠仔]')
    orderlist["tk"]=raw_input(">>>请输入出发站名:")#.decode('utf-8')
    orderlist["ar"]=raw_input(">>>请输入到达站名:")#.decode('utf-8')
    train_date=raw_input(">>>请选择日期,默认是今天!(%s):"%time.strftime('%Y-%m-%d'))
    if not train_date:
        orderlist["train_date"]=time.strftime('%Y-%m-%d')
    else:
        orderlist["train_date"]=train_date
    html=getTrain(CLeftTicketUrl,orderlist["train_date"],city[orderlist.get("tk")],city[orderlist.get("ar")])
    while not html:
        time.sleep(3)
        html=getTrain(CLeftTicketUrl,orderlist["train_date"],city[orderlist.get("tk")],city[orderlist.get("ar")])
    n=0
    list2=[]
    for i in html:
        tmp_list=i.split('|')
        list2.append((n,tmp_list[13],tmp_list[3],city2[tmp_list[6]],city2[tmp_list[7]],tmp_list[8],tmp_list[9],tmp_list[10],tmp_list[30],tmp_list[31],tmp_list[29],tmp_list[28],tmp_list[23],tmp_list[26]))
        print ('[%s]%s %s (%s-%s) [%s-%s] 历时:%s 二等:%s 一等:%s 硬座:%s 硬卧:%s 软卧:%s 无座:%s '%(n,tmp_list[13],tmp_list[3],city2[tmp_list[6]],city2[tmp_list[7]],tmp_list[8],tmp_list[9],tmp_list[10],tmp_list[30],tmp_list[31],tmp_list[29],tmp_list[28],tmp_list[23],tmp_list[26]))
        n+=1
    No=raw_input(">>>请选择车次对应的序号,多个车次请使用,隔开:")
    if ',' in No:
        for x in No.split(','):
            orderlist["train_no"].append(list2[int(x)][2])
    else:
        orderlist["train_no"]=list2[int(No)][2]
    ss={'0':'二等座','1':'一等座','2':'硬卧','3':'硬座','4':'软卧'}
    orderlist["choose_seats"]=ss[raw_input("请选择坐席,不选默认任意座位(二等座0,一等座1,硬卧2,硬座3,软卧4):")]
    print('>>>您已选择了车次,请登录后选择乘车人!')
    global username,password
    username=raw_input(">>>请输入12306账号:")
    password=raw_input(">>>请输入12306密码:")
    #c.load(ignore_expires=True,ignore_discard=True)
    list2=getPassInfo()[2]
    No=raw_input(">>>请选择乘车人序号,多个乘车人,请使用,隔开:")
    if ',' in No:
        for x in No.split(','):
            orderlist["passenger_name"]+=list2[int(x)][1]+','
            orderlist["s1"]+='%s,0,1,%s,1,%s,%s,N_'%(seat.get(orderlist["choose_seats"]),list2[int(x)][1],list2[int(x)][2],list2[int(x)][3])
            orderlist["s2"]+='%s,1,%s,1_'%(list2[int(x)][1],list2[int(x)][2])
        orderlist["passenger_name"]=orderlist["passenger_name"][:-1]
    else:
        orderlist["passenger_name"]+=list2[int(No)][1]
        orderlist["s1"]+='%s,0,1,%s,1,%s,%s,N_'%(seat.get(orderlist["choose_seats"]),list2[int(No)][1],list2[int(No)][2],list2[int(No)][3])
        orderlist["s2"]+='%s,1,%s,1_'%(list2[int(No)][1],list2[int(No)][2])
    #print orderlist
if __name__=='__main__':
     #获取查票地址
    while CLeftTicketUrl:
        if time.strftime('%H:%M:%S')>'07:00:00' and time.strftime('%H:%M:%S')<'23:00:00':
            if findtrain(orderlist["train_no"],orderlist["train_date"],city.get(orderlist["tk"]),city.get(orderlist["ar"])):
                break
            else:
                time.sleep(2)



'''
seatType:
3硬卧
1硬座,无座
4软卧
M一等座
O二等座
seatType={'二等座':'O','一等座':'M','硬卧':'3','软卧':'4','硬座':'1','无座':'1'}

0 rfPu9cd9%2FCO4fTYKlDg0pHTTRVqg6QsSgCaFh3LqjsT8iktXc3FDpW71HgrlaFjD10wL%2BijItcmG%0AIKYBLbbOC6y%2FI7ULR39mb8S1p9gWnYgDsIesosW2kfKac0sEiin8jXnC3BY1Vqu0jgaQ5Nikje6s%0Azl4YtA%2FIfbyC2RWn3eEYU%2BP4BfHZWmSypXkyOOvYKV2OcJZ1yNeysVi4ZcDJTStYniRBlwpP%2BjJ8%0AjBXQgTztdr0Y
1 预订
2 5l000G150500
3 G1505 (车次)
4 NKH   
5 NFZ
6 CWQ (上车站)
7 NFZ (下车站)
8 14:06  (出发时间)
9 19:51  (到达时间)
10 05:45 (历时)
11 Y
12 QLDC3b1%2FMGi7CRnV4Aoh5SW%2Bu92aGXTN%2BMXppgw5dC2G1uXn
13 20170919
14 3
15 H2
16 18
17 25
18 0
18 0
20 
21 
22 
23 (软卧)
24 
25 (特等座)
26 (无座)
27 
28 (硬卧)
29 (硬座)
30 有 (二等座)
31 无 (一等座)
32 无
33 
34 O0M090
35 OM9
'''
